import type { PageType } from '../../lib/page_handler/type'
import type {
  categoryNameType,
  PERSONALIZATION_STORAGE_CONFIG,
  PLATFORM_PAGE_TYPES,
} from '../constants'
import type { ComponentType } from './components'
import type { PlatformTypeValue } from './platform'

/**
 * 实例接口
 */
export interface IInstance {
  id: string
  instance: ComponentType
  // 使用交叉类型扩展
  config: BaseStyleConfig
}

/**
 * 可绑定元素接口
 */
interface IBindableElement {
  id: string
  element: JQuery<HTMLElement>
}
export type MountTarget = JQuery<HTMLElement> | IBindableElement[]

/**
 * 个性化设置项接口
 */
export interface IPersonalizationItem<T extends PersonalizationStorageType = PersonalizationStorageType> {
  /**
   * 唯一标识符
   */
  id: string
  /**
   * 名称
   */
  name: PersonalizationStorageType
  /**
   * 描述
   */
  description?: string
  /**
   * 组件类型（单个组件/组件套）
   */
  componentType: 'single' | 'collection'
  /**
   * 配置
   */
  config: IPersonalizationItemConfig
  /**
   * 支持的网站平台
   */
  supportedPlatforms: PlatformTypeValue[] | '*'
  /**
   * 支持的页面类型
   */
  supportedPages: Partial<Record<PlatformTypeValue, PageType[]>> | '*'
  /**
   * 不支持的页面类型
   */
  notSupportedPages: Partial<Record<PlatformTypeValue, PageType[]>> | undefined
  /**
   * 校验失败消息
   */
  invalidMessage?: string
  invalidMessages?: Map<string, string>
  /**
   * 存储键
   */
  storageKeys: StorageKeys<T>[]
  /**
   * 初始化失败标志
   */
  initFailed: boolean
  /**
   * 分类标识
   */
  category?: string
  /**
   * 排序权重
   */
  priority?: number
  /**
   * 渲染设置项
   * @returns 返回 HTML 字符串
   */
  render: () => string | IRenderFragment[]
  /**
   * 获取组件实例
   */
  getInstances?: () => Map<string, IInstance>
  /**
   * 获取实例ID（仅组件套需要）
   */
  getInstanceIds?: () => string[]
  /**
   * 挂载组件
   * @param element 元素引用
   */
  mount: (element: MountTarget) => void
  /**
   * 初始化设置项
   */
  onInit?: (...args: any[]) => void
  /**
   * 保存设置项
   */
  onSave?: (...args: any[]) => void
  /**
   * 重置设置项
   */
  onReset: (...args: any[]) => void
  /**
   * 应用设置项
   */
  apply: (...args: any[]) => void
  /**
   * 检查当前设置项状态
   * @returns 返回检查结果
   */
  check: (...args: any[]) => ValidResultType
}

/**
 * 渲染片段接口
 */
export interface IRenderFragment {
  id: string
  type: string
  html: string
  category: string
  priority: number
}

/**
 * 个性化项初始化配置
 */
export interface IPersonalizationItemConfig {
  className: string
  messageName: string
}

/**
 * 个性化设置存储类型
 */
export type PersonalizationStorageType = keyof typeof PERSONALIZATION_STORAGE_CONFIG

/**
 * 个性化设置项状态
 */
export interface ItemStateConfig {
  key: string
  attributes?: string
  suffix?: string
  className: string
  symbol: string
  color: string
}
export interface ItemStateCollection {
  SAVED: ItemStateConfig
  CHANGED: ItemStateConfig
  INVALID: ItemStateConfig
  SKIPPED: ItemStateConfig
}

/**
 * 获取特定模块的存储键类型
 */
export type StorageKeys<T extends PersonalizationStorageType> = typeof PERSONALIZATION_STORAGE_CONFIG[T][number]

/**
 * 选择器配置类型（支持单/多选择器）
 */
export type PersonalizationSelectorConfig
  = | string
    | (() => string)

/**
 * 背景图片配置
 */
export interface BackgroundImageConfig {
  enabled?: boolean
  id: string
  selector?: PersonalizationSelectorConfig
  category: string
  categoryKey: categoryKeyType
  priority: number
  inherit?: boolean
  styleVar: string
  cssProperty?: string
  extraStyles?: string
  wallpaper?: {
    enabled: boolean
    zIndex?: number
  }
}

/**
 * 背景图片配置
 */
export interface CustomConfig {
  id: string
  category: string
  categoryKey: categoryKeyType
  priority: number
  styleVar: string
}

/**
 * 基础样式配置
 */
export interface BaseStyleConfig {
  enabled?: boolean
  id: string
  selector: PersonalizationSelectorConfig
  category: string | null
  categoryKey: categoryKeyType
  priority: number
  inherit: boolean
  styleVar: string
  remark?: string
}
/**
 * 基础样式配置类型（单/数组）
 */
export type BaseStyleConfigType = BaseStyleConfig | BaseStyleConfig[]
/**
 * 背景图片配置类型（单/数组）
 */
export type BackgroundImageConfigType = BackgroundImageConfig | BackgroundImageConfig[]

/**
 * 样式配置映射类型
 */
export interface StyleConfigMap {
  backgroundImage: BackgroundImageConfigType
  image: BaseStyleConfigType
  elementHide: BaseStyleConfigType
  pageTheme: BaseStyleConfigType
  loadingTheme: BaseStyleConfigType
  loadingPhrases: BaseStyleConfigType
  styleAdjust: BaseStyleConfigType
  customCss: CustomConfig
  customJs: CustomConfig
  shortcuts: BaseStyleConfigType
  searchResultColumns: BaseStyleConfigType
  searchResultNum: BaseStyleConfigType
  popularLink: BaseStyleConfigType
  pageNum: BaseStyleConfigType
}
/**
 * 样式配置键类型
 */
export type StyleConfigKey = keyof StyleConfigMap
/**
 * 页面框架区域配置
 */
export interface PageFrameworkConfig extends Partial<StyleConfigMap> {
  enabled?: boolean
}
/**
 * 框架区域键
 */
export type FrameworkKeys<T extends PlatformPageTypeValue>
  = T extends 'blog' ? keyof typeof PLATFORM_PAGE_TYPES.BLOG.framework
    : T extends 'tiebar' ? keyof typeof PLATFORM_PAGE_TYPES.TIEBAR.framework
      : T extends 'search' ? keyof typeof PLATFORM_PAGE_TYPES.SEARCH.framework
        : T extends 'video' ? keyof typeof PLATFORM_PAGE_TYPES.VIDEO.framework
          : T extends 'others' ? keyof typeof PLATFORM_PAGE_TYPES.OTHERS.framework
            : never

/**
 * 页面类型值
 */
export type PlatformPageTypeValue = typeof PLATFORM_PAGE_TYPES[keyof typeof PLATFORM_PAGE_TYPES]['value']

/**
 * 平台全局配置
 */
export interface PlatformGlobalConfig {
  defaults?: {
    backgroundImage?: BackgroundImageConfig
    customCss?: CustomConfig
    customJs?: CustomConfig
    styleAdjust?: BaseStyleConfig
  }
}

/**
 * 页面类型配置
 */
export interface PageTypeConfig<T extends PlatformPageTypeValue> {
  framework: Record<FrameworkKeys<T>, PageFrameworkConfig>
  customAreas?: Record<string, PageFrameworkConfig>
}
/**
 * 博客平台框架配置类型
 */
export type BlogFrameworkConfig = Record<FrameworkKeys<'blog'>, PageFrameworkConfig>
/**
 * 贴吧平台框架配置类型
 */
export type TiebarFrameworkConfig = Record<FrameworkKeys<'tiebar'>, PageFrameworkConfig>
/**
 * 搜索平台框架配置类型
 */
export type SearchFrameworkConfig = Record<FrameworkKeys<'search'>, PageFrameworkConfig>
/**
 * 视频平台框架配置类型
 */
export type VideoFrameworkConfig = Record<FrameworkKeys<'video'>, PageFrameworkConfig>
/**
 * 其他平台框架配置类型
 */
export type OthersFrameworkConfig = Record<FrameworkKeys<'others'>, PageFrameworkConfig>

/**
 * 完整平台配置
 */
export interface FullPlatformConfig<T extends PlatformPageTypeValue = PlatformPageTypeValue> {
  type: T
  enabled?: boolean
  global?: PlatformGlobalConfig
  contents: PageTypeConfig<T>
}

/**
 * 平台元素配置
 */
export interface PlatformElementConfig {
  id: categoryNameType
  category: string | null
  categoryKey: categoryKeyType
  priority: number
  selector: string
  inherit: boolean
  styleVar: string
  edit?: boolean
  remark?: string
  isCurrentPage?: (url: string) => boolean // 判断是否属于当前页面
}

export interface StorageMapKeys {
  value: string
  mode: string
  changed: string
  saved: string
  [key: string]: string // 允许子类扩展
}

export interface StorageMapValues {
  value: string
  mode: string
  changed: boolean
  saved: boolean
  [key: string]: unknown // 允许子类扩展
}

export type categoryKeyType = 'category' | 'id'
